package net.butfly.albacore.logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
import org.springframework.core.io.ClassPathResource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

class Log4jFactory {
	private Log4jFactory() {}

	private static final String[] configs = new String[] { "log4j.xml", "log4j.properties",
			"net/butfly/albacore/core/logger/log4j.properties" };

	public static void init() throws SAXException, IOException, ParserConfigurationException {
		InputStream in = null;
		for (String conf : configs) {
			try {
				in = new ClassPathResource(conf).getInputStream();
				if (conf.endsWith(".xml")) {
					Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
					DOMConfigurator.configure(doc.getDocumentElement());
					return;
				} else if (conf.endsWith(".properties")) {
					Properties prop = new Properties();
					prop.load(in);
					PropertyConfigurator.configure(prop);
					return;
				}
			} catch (Exception ex) {} finally {
				if (null != in) in.close();
			}
		}
		throw new ParserConfigurationException("Cannot find default or customized config file for log4j.");
	}
}
